import type {
  InventoryAdjustParams,
  InventoryMoveParams,
  InventorySearchParams,
  InventoryTransaction,
  Location,
  Warehouse,
} from './types';

/**
 * 库存模块服务层，封装与后端交互的API调用
 */
import { message } from 'ant-design-vue';

import {
  adjustInventory as adjustInventoryApi,
  exportInventoryData as exportInventoryDataApi,
  getInventoryList as getInventoryListApi,
  getInventoryMovements as getInventoryMovementsApi,
  moveInventory as moveInventoryApi,
} from '#/api/inventory/inventory';
import { getLocationList as getLocationListApi } from '#/api/inventory/location';
import { getWarehouseList as getWarehouseListApi } from '#/api/inventory/warehouse';
import { $t } from '#/locales';

/**
 * 获取库存列表
 * @param params 搜索参数
 * @param options 配置选项
 * @returns Promise 对象，包含库存列表数据和总数
 */
export async function getInventoryList(
  params: InventorySearchParams,
  options?: { showError?: boolean; showLoading?: boolean },
): Promise<{ data: any[]; total: number }> {
  const { showLoading = false, showError = true } = options || {};
  try {
    if (showLoading) {
      // 可以在这里添加全局加载状态
    }
    const result = await getInventoryListApi(params);
    // 兼容不同的返回格式
    if (result?.data) {
      return { data: result.data, total: result.total || 0 };
    } else if (Array.isArray(result)) {
      return { data: result, total: result.length };
    }
    return { data: [], total: 0 };
  } catch (error) {
    if (showError) {
      message.error(error?.message || $t('inventory.loadFailed'));
    }
    throw error;
  } finally {
    if (showLoading) {
      // 可以在这里移除全局加载状态
    }
  }
}

/**
 * 获取库存交易记录
 * @param params 搜索参数
 * @param options 配置选项
 * @returns Promise 对象，包含交易记录数据
 */
export async function getInventoryTransactions(
  params: { inventory_id: number | string; page_size?: number },
  options?: { showError?: boolean },
): Promise<{ data: InventoryTransaction[] }> {
  const { showError = true } = options || {};
  try {
    const result = await getInventoryMovementsApi({
      page_size: 100,
      ...params,
    });
    // 兼容不同的返回格式
    if (result?.data) {
      return { data: result.data };
    } else if (Array.isArray(result)) {
      return { data: result };
    }
    return { data: [] };
  } catch (error) {
    if (showError) {
      message.error($t('inventory.detailModal.loadMovementFailed'));
    }
    throw error;
  }
}

/**
 * 调整库存
 * @param params 调整参数
 * @param options 配置选项
 * @returns Promise 对象，表示调整结果
 */
export async function adjustInventory(
  params: InventoryAdjustParams,
  options?: {
    showError?: boolean;
    showLoading?: boolean;
    showSuccess?: boolean;
  },
): Promise<boolean> {
  const {
    showLoading = false,
    showSuccess = true,
    showError = true,
  } = options || {};
  try {
    if (showLoading) {
      // 可以在这里添加全局加载状态
    }
    await adjustInventoryApi(params);
    if (showSuccess) {
      message.success($t('inventory.adjustModal.success'));
    }
    return true;
  } catch (error) {
    if (showError) {
      message.error(error?.message || $t('inventory.adjustModal.failed'));
    }
    throw error;
  } finally {
    if (showLoading) {
      // 可以在这里移除全局加载状态
    }
  }
}

/**
 * 移动库存
 * @param params 移动参数
 * @param options 配置选项
 * @returns Promise 对象，表示移动结果
 */
export async function moveInventory(
  params: InventoryMoveParams,
  options?: {
    showError?: boolean;
    showLoading?: boolean;
    showSuccess?: boolean;
  },
): Promise<boolean> {
  const {
    showLoading = false,
    showSuccess = true,
    showError = true,
  } = options || {};
  try {
    if (showLoading) {
      // 可以在这里添加全局加载状态
    }
    await moveInventoryApi(params);
    if (showSuccess) {
      message.success($t('inventory.moveModal.success'));
    }
    return true;
  } catch (error) {
    if (showError) {
      message.error(error?.message || $t('inventory.moveModal.failed'));
    }
    throw error;
  } finally {
    if (showLoading) {
      // 可以在这里移除全局加载状态
    }
  }
}

/**
 * 导出库存数据
 * @param params 导出参数
 * @returns Promise 对象，包含导出文件的Blob对象
 */
export async function exportInventoryData(
  params: InventorySearchParams,
): Promise<any | Blob> {
  try {
    message.loading($t('inventory.exporting'));
    const result = await exportInventoryDataApi({ page_size: 1000, ...params });
    message.destroy();
    message.success($t('inventory.exportSuccess'));
    return result;
  } catch (error) {
    message.destroy();
    message.error(error?.message || $t('inventory.exportFailed'));
    throw error;
  }
}

/**
 * 获取仓库列表
 * @param options 配置选项
 * @returns Promise 对象，包含仓库列表
 */
export async function getWarehouseList(options?: {
  showError?: boolean;
}): Promise<Warehouse[]> {
  const { showError = true } = options || {};
  try {
    const result = await getWarehouseListApi({ page_size: 999 });
    // 兼容不同的返回格式
    if (Array.isArray(result)) {
      return result;
    } else if (result?.data?.items) {
      return result.data.items;
    } else if (result?.items) {
      return result.items;
    }
    return [];
  } catch (error) {
    if (showError) {
      message.error(
        error?.message || $t('inventory.moveModal.warehouseListFailed'),
      );
    }
    return [];
  }
}

/**
 * 获取库位列表
 * @param warehouseId 仓库ID
 * @param options 配置选项
 * @returns Promise 对象，包含库位列表
 */
export async function getLocationList(
  warehouseId?: number | string,
  options?: { showError?: boolean },
): Promise<Location[]> {
  const { showError = true } = options || {};
  try {
    const params = warehouseId
      ? { warehouse_id: warehouseId, page_size: 999 }
      : { page_size: 999 };
    const result = await getLocationListApi(params);
    // 兼容不同的返回格式
    if (Array.isArray(result)) {
      return result;
    } else if (result?.data?.items) {
      return result.data.items;
    } else if (result?.items) {
      return result.items;
    }
    return [];
  } catch (error) {
    if (showError) {
      message.error(
        error?.message || $t('inventory.moveModal.locationListFailed'),
      );
    }
    return [];
  }
}
